const orderService = require('../service/OrderService');
const OrderBookDto = require('../dto/OrderBookDto');

// ---------- lambda entry ----------

/**
 * getMatchPrice
 * @param {Object} event
 * @param {Object} context
 * @return {Object}
 */
async function getMatchPrice(event, context) {
  let { baseCoin, counterCoin } = event.pathParameters;

  let buyMaxPrice = orderService.fetchMaxBuyPrice(baseCoin, counterCoin);
  let sellMinPrice = orderService.fetchMinSellPrice(baseCoin, counterCoin);

  let prices = await Promise.all([buyMaxPrice, sellMinPrice]);

  console.info('prices results:', prices);

  return { maxBuyPrice: prices[0], minSellPrice: prices[1] };
}

/**
 * listBuyOrders
 * @param {Object} event
 * @param {Object} context
 * @return {Array<Order>}
 */
async function listBuyOrders(event, context) {
  let { minPrice, baseCoin, counterCoin } = event.body;

  let orders = await orderService.listBuyOrdersWithMinPrice(minPrice, baseCoin, counterCoin);

  return orders;
}

/**
 * listSellOrders
 * @param {Object} event
 * @param {Object} context
 * @return {Array<Order>}
 */
async function listSellOrders(event, context) {
  let { maxPrice, baseCoin, counterCoin } = event.body;

  let orders = await orderService.listSellOrdersWithMaxPrice(maxPrice, baseCoin, counterCoin);

  return orders;
}

/**
 * topBook
 * @param {Object} event
 * @param {Object} context
 * @return {OrderBookDto}
 */
async function topBook(event, context) {
  const { coinPair, top } = event.body;
  const [baseCoinType, counterCoinType] = coinPair.split('/');

  let [buyOrderTop, sellOrderTop] = await orderService.topBook(
    baseCoinType,
    counterCoinType,
    Number(top)
  );

  return new OrderBookDto({ buyOrderTop, sellOrderTop, top });
}

module.exports = {
  getMatchPrice,
  listBuyOrders,
  listSellOrders,
  topBook,
};

// ---------- internal functions ----------
